package com.yj.core.util;


import com.yj.core.exception.ServiceException;
import com.yj.core.result.BaseExceptionMsg;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Random;

public class SecurityUtil {

    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * MD5 加密类型
     */
    public enum MD5_LENGTH {

        LENGTH_16(16),
        LENGTH_32(21);

        int length;

        MD5_LENGTH(int length) {

            this.length = length;
        }
    }


    /**
     * md5加密(加盐)
     *
     * @param password
     * @param salt
     * @return
     */
    public static String md5Hex(String password, String salt) {
        return md5Hex(password + salt);
    }

    /**
     * md5加密(不加盐)
     *
     * @param str
     * @return
     */
    public static String md5Hex(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(str.getBytes());
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < bs.length; i++) {
                if (Integer.toHexString(0xFF & bs[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & bs[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & bs[i]));
                }
            }
            return md5StrBuff.toString();
        } catch (Exception e) {
            throw new ServiceException("加解密失败");
        }
    }

    /**
     * 获取指定位数的随机数
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 编码为 base64
     * @param src
     * @return
     */
    public static String encodeForBase64(String src){

        try {
            return Base64.encodeBase64String(src.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(BaseExceptionMsg.EXECUTE_FAILD);
        }
    }

    /**
     * 解码为 base64
     *
     * @param src
     * @return
     */
    public static String decodeForBase64(String src){

        try {
            return new String(Base64.decodeBase64(src), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(BaseExceptionMsg.EXECUTE_FAILD);
        }
    }

}
